package com.shmet.tool.localcalltwo.frame.context;


import com.shmet.tool.localcalltwo.frame.ann.LocalReference;
import com.shmet.tool.localcalltwo.frame.proxy.BusJdkProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;

/**
 * @author shmet
 * @date 2022/7/28 15:46
 * @desc 实现自动注入
 */
@Component
public class BeanAutoWrite implements InstantiationAwareBeanPostProcessor {

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        try {
            Class<?> clazz = bean.getClass();
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(LocalReference.class)) {
                    Object proxyInstance = new BusJdkProxy(field.getType()).getProxy();
                    ReflectionUtils.makeAccessible(field);
                    field.set(bean, proxyInstance);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return pvs;
    }
}